package com.kd.service.employee;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kd.common.PageResult;
import com.kd.dao.EmployeeMapper;
import com.kd.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 员工服务实现类，继承自 MyBatis-Plus 的 ServiceImpl
 * 1.通过eid找员工
 * 2.通过身份证找eid
 * 3.通过手机号找eid
 * 4.5.查看所有员工列表，with过滤条件
 * 6.插入员工
 * 7.修改属性
 * 8.获取员工数量
 *
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    private final Integer INSERT_SUCESS=1;

    // ===== 查询类方法 =====

    /**
     * 1.通过id找员工
     */
    @Override
    public Employee findEmployeeByEId(int id) {
        return employeeMapper.selectById(id);
    }
    public Employee findEmployeeByEId(String id) {
        return employeeMapper.selectById(id);
    }
    /**
     * 2.通过身份证找id
     */
    @Override
    public Integer getEidByCardid(String cardid) {
        if (StringUtils.isBlank(cardid)) return null;
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("cardid", cardid);
        Employee employee = employeeMapper.selectOne(wrapper);
        return employee != null ? employee.getEid() : null;
    }

    /**
     * 3.通过手机号找id
     */
    @Override
    public Integer getEidByphone(String phone) {
        if (StringUtils.isBlank(phone)) return null;
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        Employee employee = employeeMapper.selectOne(wrapper);
        return employee != null ? employee.getEid() : null;
    }



    /**
     * 4.5基于游标的分页查询 - 通用过滤查询
     */
    @Override
    public PageResult<Employee,Integer> findEmployeeListWithFilters(
            Integer cursor,
            Integer limit,
            Integer eid,
            String name,
            Date hiredate,
            Integer status,
            Boolean hasImage,
            Integer permission) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        // 添加过滤条件
        if (eid != null) {
            wrapper.eq("eid", eid); // 精确匹配员工ID
        }
        if (StringUtils.isNotBlank(name)) {
            wrapper.like("name", name); // 模糊匹配姓名
        }
        if (hiredate != null) {
            wrapper.eq("hiredate", hiredate); // 精确匹配入职日期
        }
        if (status != null) {
            wrapper.eq("status", status); // 精确匹配状态
        }

        if (hasImage != null) {
            if (hasImage) {
                wrapper.isNotNull("image").ne("image", "");
            } else {
                wrapper.isNull("image").or().eq("image", "");
            }
        }

        if (permission != null) {
            wrapper.eq("permission", permission); // 精确匹配权限
        }
        // 游标条件（基于eid的分页）
        if (cursor != null && cursor > 0) {
            wrapper.lt("eid", cursor);
        }
        // 按eid倒序排列，确保分页连续性
        wrapper.orderByDesc("eid");
        // 查询 limit + 1 条，用于判断是否有下一页
        List<Employee> employees = employeeMapper.selectList(
                wrapper.last("LIMIT " + (limit + 1))
        );
        boolean hasNext = employees.size() > limit;
        List<Employee> resultData = hasNext ?
                employees.subList(0, limit) : employees;
        // 获取下一页的游标（最后一条记录的eid）
        Integer nextCursor = null;
        if (hasNext && !resultData.isEmpty()) {
            nextCursor = resultData.get(resultData.size() - 1).getEid();
        }
        return PageResult.of(resultData, nextCursor, hasNext, limit);
    }




    // ===== 插入类方法 =====

    /**
     * 6.插入新员工（密码加密处理）
     */
    @Override
    public boolean insert(Employee employee) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        employee.setPassword(passwordEncoder.encode(employee.getPassword()));
        return employeeMapper.insert(employee)==INSERT_SUCESS;
    }

    // ===== 修改类方法 =====
    /**
     * 7.修改对应属性
     */
    @Override
    public boolean updateEmployee(Employee employee) {
        return employeeMapper.updateById(employee)>0;
    }

    /**
     * 8.获取员工数量
     */
    @Override
    public int getEmployeeCount() {
        // 调用mapper层的方法获取总数量
        return employeeMapper.selectCount(null);
    }


    @Override
    public Employee setPermission(Integer eid, Integer permission) {
        // 验证权限值是否合法
        if (permission < 0 || permission > 2) {
            throw new IllegalArgumentException("权限值必须在0-2范围内");
        }
        // 获取员工信息
        Employee employee = this.findEmployeeByEId(eid);
        if (employee == null) {
            throw new RuntimeException("员工不存在");
        }
        // 更新权限
        employee.setPermission(permission);
        this.updateEmployee(employee);

        return employee;
    }


}
